local M = { }

local log = require("log"):new("tanks.svc")
local pb = require("protobuf")
local empty_msg_data = pb.encode("rpc.EmptyMsg", { })
local matcher = require("tanks.matcher")
local room_mgr = require("tanks.room_mgr")

log:debug("loading service...")

local function get_room(game_clt_id)
    return room_mgr.get(game_clt_id)
end  -- get_room

function M.EnterMatch(ctx, content)
    log:debug("EnterMatch")
    c_rpc.reply_to(ctx, empty_msg_data)
    matcher.enter(ctx:get_game_clt_id())
end  -- EnterMatch()

function M.Exit(ctx, content)
    log:debug("Exit")
    matcher.exit(ctx:get_game_clt_id())
    c_rpc.reply_to(ctx, empty_msg_data)
end  -- ExitMatch()

function M.MoveTo(ctx, content)
    log:debug("MoveTo")
    local req = pb.decode("tanks.PositionMsg", content)
    c_rpc.reply_to(ctx, empty_msg_data)
    local game_clt_id = ctx:get_game_clt_id()
    local room = get_room(game_clt_id)
    log:debug("get room %s -> %s", game_clt_id:to_string(), room)
    if not room then return end
    room:player_move_to(game_clt_id, req)
end  -- MoveTo()

-- 转向
function M.RotateTo(ctx, content)
    log:debug("RotateTo")
    local req = pb.decode("tanks.RotationMsg", content)
    -- local game_clt_id = ctx:get_game_clt_id()
    c_rpc.reply_to(ctx, empty_msg_data)
    local game_clt_id = ctx:get_game_clt_id()
    local room = get_room(game_clt_id)
    log:debug("get room %s -> %s", game_clt_id:to_string(), room)
    if not room then return end
    room:player_rotate_to(game_clt_id, req)
end  -- RotateTo()

-- 发射炮弹
function M.Fire(ctx, content)
    log:debug("Fire")
    local req = pb.decode("tanks.FireMsg", content)
    -- local game_clt_id = ctx:get_game_clt_id()
    c_rpc.reply_to(ctx, empty_msg_data)
    local game_clt_id = ctx:get_game_clt_id()
    local room = get_room(game_clt_id)
    log:debug("get room %s -> %s", game_clt_id:to_string(), room)
    if not room then return end
    room:player_fire_to(game_clt_id, req)
end  -- Fire()

-- 炮弹爆炸。同一炮弹，双方各自向服务器报告爆炸结果。
-- 服务器统一推送伤害值：TanksPush::Damage(DamageMsg)
function M.ShellExplode(ctx, content)
    log:debug("ShellExplode")
    local req = pb.decode("tanks.ShellExplosionMsg", content)
    -- local game_clt_id = ctx:get_game_clt_id()
    c_rpc.reply_to(ctx, empty_msg_data)
    -- Todo
    local game_clt_id = ctx:get_game_clt_id()
    local room = get_room(game_clt_id)
    log:debug("get room %s -> %s", game_clt_id:to_string(), room)
    if not room then return end
    room:shell_explode_to(game_clt_id, req)
end  -- ShellExplode()

require("rpc_request_handler").register_service("tanks.Tanks", M)
return M
